import store from '../store'
import dateDiff from '@/utils/DateDiff'
import changeDate from '@/utils/changeDate'


class SocketObj {
    constructor(socketUrl) {

        this.socketUrl = socketUrl || '';
        this.heartTimer = null
        this.autoConnect = null
        this.token = uni.getStorageSync('token')
    }

    _initWebSocket() {
        uni.connectSocket({
            // url: 'ws://123.207.167.163:9010/ajaxchattest',
            // url: `ws://192.168.1.212:8890/msg/sel/${this.token}`,
            url: `ws://120.40.77.185:59985/msg/sel/${this.token}`,
            header: {
                "content-type": "application/json"
            },
            method: "POST",
            success: () => {
                console.log("连接成功");
            },
            fail() {
                console.log("connectSocket连接失败");
            }
        });
        uni.onSocketOpen(() => {
            console.log("WebSocket连接打开");
            clearInterval(this.autoConnect),
                uni.sendSocketMessage({
                    data: "p",
                    success() {
                        console.log("发送消息成功");
                    },
                    fail: res => {
                        console.log('发送消息失败');
                    }
                });
            this.heart()
        });
        uni.onSocketError(function(res) {
            console.log("WebSocket连接打开失败");
        });

        uni.onSocketClose((res) => {
            console.log("WebSocket 已关闭！");
            this.autoConnect = setTimeout(() => { //断线重连
                console.log('断线重连')
                this._initWebSocket();
            }, 5000);
        });
        this.receive()
    }

    receive(cb) {
        uni.onSocketMessage((res) => {
            res = JSON.parse(res.data)
            console.log(res)
            let buyerList = uni.getStorageSync('buyerList') || [];
            let informList = uni.getStorageSync('informList') || [];
            let messageTotal = 0
                // console.log('收到消息', res)
            if (res.cmd = 'u2u' && res.cb) {
                let head = res.data.ar
                console.log(head)
                let content = JSON.parse(res.cb)
                console.log(content)

                let result = buyerList.some(item => {
                    if (item.current == content.current) {
                        return true
                    }
                })

                if (!result) {
                    content.num = 1
                    buyerList.push(content)
                    buyerList[0].head = head
                } else {
                    buyerList.forEach((item, i, arr) => {
                        if (item.current == content.current) {
                            buyerList[i].msg = content.msg
                            buyerList[i].msgtime = content.msgtime
                            buyerList[i].head = head
                            buyerList[i].num++
                        }
                    })
                }

                cb && cb(content)
            }
            let arrMsgTotal = [...buyerList, ...informList]
            arrMsgTotal.forEach(item => {
                messageTotal += item.num
            })

            uni.setTabBarBadge({
                index: 1,
                text: String(messageTotal)
            })
            uni.setStorageSync('messageTotal', messageTotal);
            uni.setStorageSync('buyerList', buyerList);
            store.dispatch(`messageTotal/get_messageTotal`, messageTotal);
            store.dispatch(`buyerList/get_buyerList`, buyerList);

        });
    }

    heart() { //心跳
        this.heartTimer = setInterval(() => {
            uni.sendSocketMessage({
                data: "p",
                success() {
                    console.log("心跳");
                }
            });
        }, 30000);
    }

    close() {
        uni.onSocketOpen(function() {
            uni.closeSocket();
        });
    }
}

export default SocketObj